<template>
	<div class="personal layout-pd">
		<el-row>
			<!-- 个人信息 -->
			<el-col :xs="24" :sm="24">
				<el-card shadow="hover" header="个人信息">
					<div class="personal-user">
						<div class="personal-user-left">
							<el-upload
								:on-change="handleChange"
								:show-file-list="false"
								action="#"
								auto-upload="false"
								accept=".jpg, .png, .jpeg"
								class="h100 personal-user-left-upload"
								:limit="1"
							>
								<img :src="imgSrc" />
							</el-upload>
						</div>
						<div class="personal-user-right">
							<el-row>
								<el-col :span="24" class="personal-title mb18">{{ currentTime }},尊敬的用户,欢迎访问硬件实验成绩评定系统! </el-col>
								<el-col :span="24">
									<el-row>
										<el-col :xs="24" :sm="16" class="personal-item mb6">
											<div class="personal-item-label">{{ state.idLabel }}:</div>
											<div class="personal-item-value">{{ state.id }}</div>
										</el-col>
										<el-col :xs="24" :sm="8" class="personal-item mb6">
											<div class="personal-item-label">用户名:</div>
											<div class="personal-item-value">{{ state.userName }}</div>
										</el-col>
									</el-row>
								</el-col>
								<el-col :span="24">
									<el-row>
										<el-col :xs="24" :sm="16" class="personal-item mb6">
											<div class="personal-item-label">联系方式:</div>
											<div class="personal-item-value">{{ state.phone }}</div>
										</el-col>
										<el-col :xs="24" :sm="8" class="personal-item mb6" v-show="state.ifStudent">
											<div class="personal-item-label">班级:</div>
											<div class="personal-item-value">{{ lesson_name }}</div>
										</el-col>
									</el-row>
								</el-col>
							</el-row>
						</div>
					</div>
				</el-card>
			</el-col>

			<!-- 项目风格 -->
			<el-col :span="24">
				<el-card shadow="hover" class="mt15" header="项目风格">
					<el-carousel :interval="3000" type="card" height="200px">
						<el-carousel-item v-for="item in carouselData" :key="item">
							<el-image class="carousel_image" :src="item.url" />
						</el-carousel-item>
					</el-carousel>
				</el-card>
			</el-col>

			<!-- 更新信息 -->
			<el-col :span="24">
				<el-card shadow="hover" class="mt15 personal-edit" header="更新信息">
					<div class="personal-edit-title">基本信息</div>
					<el-form ref="formRef" :model="state.personalForm" size="default" label-width="100px" class="mt50 mb50">
						<el-row :gutter="35">
							<el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4" :offset="2" class="mb20">
								<el-form-item label="用户名" prop="name">
									<el-input v-model="state.personalForm.name" placeholder="请输入用户名" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" :offset="2" class="mb20">
								<el-form-item label="联系方式" prop="phone">
									<el-input v-model="state.personalForm.phone" placeholder="请输入联系方式" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" :offset="2" class="mb20" v-show="state.ifStudent">
								<el-form-item label="班级" prop="class">
									<el-select
										loading-text="加载中"
										no-match-text="无匹配数据"
										no-data-text="无数据"
										clearable
										v-model="state.personalForm.class"
										filterable
										placeholder="请选择班级"
									>
										<el-option v-for="item in state.options" :key="item.value" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :offset="8">
								<el-form-item>
									<el-button type="primary" @click="onSubmit()">
										<el-icon>
											<ele-Position />
										</el-icon>
										更新个人信息
									</el-button>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="personal">
import { reactive, computed, ref } from 'vue';
import { formatAxis } from '/@/utils/formatTime';
import { Session } from '/@/utils/storage';
import integrate from '/@/assets/personal/integrate.png';
import obtain from '/@/assets/personal/obtain.png';
import search from '/@/assets/personal/search.png';
import talk from '/@/assets/personal/talk.png';
import task from '/@/assets/personal/task.png';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { decrypt, encrypt } from '/@/utils/RSA';
import { ElMessage } from 'element-plus';
import {
	updateAdminInfo,
	updateTeacherInfo,
	updateStudentInfo,
	lessonInfo,
	getLessonInfo,
	updateTeacherImg,
	updateStudentImg,
	updateAdministratorImg,
} from '/@/api/personal';

const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
const lesson_name = ref('');
const imgSrc =
	userInfos.value.avatar === ''
		? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
		: userInfos.value.avatar;
const carouselData = [{ url: integrate }, { url: obtain }, { url: search }, { url: talk }, { url: task }];

const getRole = async () => {
	const userInfo = Session.get('userInfo');
	state.userName = userInfo.userName;
	state.phone = decrypt(userInfo.phone);
	state.id = userInfo.Id;
	if (userInfo.roles[0] == 'teacher') {
		state.idLabel = '教工号';
	} else if (userInfo.roles[0] == 'student') {
		state.idLabel = '学号';
		state.ifStudent = true;
		getLessonInfo(userInfo.lesson_id).then((res) => {
			if (res.code === '2000') {
				lesson_name.value = res.data[0].lesson_name;
			} else {
				ElMessage.error('获取用户班级信息失败');
			}
		});
		lessonInfo()
			.then((res) => {
				if (res.code === '2000') {
					state.options = res.data.map((item: any) => {
						return { label: item.lesson_name, value: item.lesson_id };
					});
				} else {
					ElMessage.error('获取班级信息失败');
				}
			})
			.catch((err) => {
				ElMessage.error('获取班级信息失败' + err);
			});
	} else {
		state.idLabel = '账号';
	}
};

// 定义变量内容
const formRef = ref(null);
const state = reactive<PersonalState>({
	id: '',
	idLabel: '',
	userName: '',
	phone: '',
	ifStudent: false,
	personalForm: {
		name: '',
		phone: '',
		class: '',
	},
	options: [{ value: '', label: '' }],
});

// 当前时间提示语
const currentTime = computed(() => {
	getRole();
	return formatAxis(new Date());
});
// 上传头像
const handleChange = (file: any) => {
	const reader = new FileReader();
	reader.readAsDataURL(file.raw);
	reader.onload = (e) => {
		const avatarInfo = Session.get('userInfo');
		avatarInfo.avatar = e.target.result;
		Session.set('userInfo', avatarInfo);
		if (Session.get('userInfo').roles[0] === 'teacher') {
			updateTeacherImg({ avatar: e.target.result }).then((res) => {
				if (res.code === '2000') {
					ElMessage.success('头像上传成功!');
					window.location.reload();
				} else {
					ElMessage.error('头像上传失败!');
				};
			});
		} else if (Session.get('userInfo').roles[0] === 'student') {
			updateStudentImg({ avatar: e.target.result }).then((res) => {
				if (res.code === '2000') {
					ElMessage.success('头像上传成功!');
					window.location.reload();
				} else {
					ElMessage.error('头像上传失败!');
				};
			});
		} else {
			updateAdministratorImg({ avatar: e.target.result }).then((res) => {
				if (res.code === '2000') {
					ElMessage.success('头像上传成功!');
					window.location.reload();
				} else {
					ElMessage.error('头像上传失败!');
				};
			});
		}
	};
};

// 修改个人信息
const onSubmit = () => {
	if (state.personalForm.name != '' || state.personalForm.phone != '' || state.personalForm.class != '') {
		const userInfo = Session.get('userInfo');
		if (userInfo.roles[0] == 'administrator') {
			const administratorInfo = {
				administrator_name: state.personalForm.name,
				phone: state.personalForm.phone,
			};
			updateAdminInfo(administratorInfo).then((res) => {
				if (res.code == '2000') {
					ElMessage.success('修改成功');
					userInfo.userName = state.personalForm.name === '' ? userInfo.userName : state.personalForm.name;
					userInfo.phone = state.personalForm.phone === '' ? userInfo.phone : encrypt(state.personalForm.phone);
					Session.set('userInfo', userInfo);
					getRole();
					formRef.value?.resetFields();
				} else {
					ElMessage.error('修改失败');
				}
			});
		} else if (userInfo.roles[0] == 'teacher') {
			const teacherInfo = {
				teacher_name: state.personalForm.name,
				phone: state.personalForm.phone,
			};
			updateTeacherInfo(teacherInfo).then((res) => {
				if (res.code === '2000') {
					ElMessage.success('修改成功');
					userInfo.userName = state.personalForm.name === '' ? userInfo.userName : state.personalForm.name;
					userInfo.phone = state.personalForm.phone === '' ? userInfo.phone : encrypt(state.personalForm.phone);
					Session.set('userInfo', userInfo);
					getRole();
					formRef.value?.resetFields();
				} else {
					ElMessage.error('修改失败');
				}
			});
		} else if (userInfo.roles[0] == 'student') {
			const studentInfo = {
				student_name: state.personalForm.name,
				phone: state.personalForm.phone,
				lesson_id: state.personalForm.class,
			};
			updateStudentInfo(studentInfo).then((res) => {
				if (res.code === '2000') {
					ElMessage.success('修改成功');
					userInfo.userName = state.personalForm.name === '' ? userInfo.userName : state.personalForm.name;
					userInfo.phone = state.personalForm.phone === '' ? userInfo.phone : encrypt(state.personalForm.phone);
					userInfo.lesson_id = state.personalForm.class === '' ? userInfo.lesson_id : state.personalForm.class;
					Session.set('userInfo', userInfo);
					getRole();
					formRef.value?.resetFields();
				} else {
					ElMessage.error('修改失败');
				}
			});
		}
	} else {
		ElMessage.error('以上信息至少一项不为空');
	}
};
</script>

<style scoped lang="scss">
@import '../../theme/mixins/index.scss';
.personal {
	.personal-user {
		height: 130px;
		display: flex;
		align-items: center;
		.personal-user-left {
			width: 100px;
			height: 130px;
			border-radius: 3px;
			:deep(.el-upload) {
				height: 100%;
			}
			.personal-user-left-upload {
				img {
					width: 130%;
					height: 100%;
					border-radius: 3px;
				}
				&:hover {
					img {
						animation: logoAnimation 0.3s ease-in-out;
					}
				}
			}
		}
		.personal-user-right {
			flex: 1;
			padding: 0 60px;
			.personal-title {
				font-size: 18px;
				@include text-ellipsis(1);
			}
			.personal-item {
				display: flex;
				align-items: center;
				font-size: 15px;
				.personal-item-label {
					color: var(--el-text-color-secondary);
					@include text-ellipsis(1);
				}
				.personal-item-value {
					@include text-ellipsis(1);
				}
			}
		}
	}
	.personal-edit {
		.personal-edit-title {
			position: relative;
			padding-left: 10px;
			color: var(--el-text-color-regular);
			&::after {
				content: '';
				width: 2px;
				height: 10px;
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				background: var(--el-color-primary);
			}
		}
		.personal-edit-safe-box {
			border-bottom: 1px solid var(--el-border-color-light, #ebeef5);
			padding: 15px 0;
			.personal-edit-safe-item {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.personal-edit-safe-item-left {
					flex: 1;
					overflow: hidden;
					.personal-edit-safe-item-left-label {
						color: var(--el-text-color-regular);
						margin-bottom: 5px;
					}
					.personal-edit-safe-item-left-value {
						color: var(--el-text-color-secondary);
						@include text-ellipsis(1);
						margin-right: 15px;
					}
				}
			}
			&:last-of-type {
				padding-bottom: 0;
				border-bottom: none;
			}
		}
	}
}

.carousel_image {
	object-fit: scale-down;
	width: 100%;
	height: 100%;
}
</style>
